package rxgo

import (
	"context"
	"fmt"
	"reflect"
	"sync"
)

// 参考transform.go中的transOperater
type filterOperator struct {
	opFunc func(ctx context.Context, o *Observable, item reflect.Value, out chan interface{}) (end bool)
}

//参考transform.go中的op函数
func (ftop filterOperator) op(ctx context.Context, o *Observable) {
	in := o.pred.outflow
	out := o.outflow
	var wg sync.WaitGroup
	go func() {
		end := false
		for x := range in {
			if end {
				break
			}
			// can not pass a interface as parameter (pointer) to gorountion for it may change its value outside!
			xv := reflect.ValueOf(x)
			// send an error to stream if the flip not accept error
			if e, ok := x.(error); ok && !o.flip_accept_error {
				o.sendToFlow(ctx, e, out)
				continue
			}
			// scheduler
			switch threading := o.threading; threading {
			case ThreadingDefault:
				if ftop.opFunc(ctx, o, xv, out) {
					end = true
				}
			case ThreadingIO:
				fallthrough
			case ThreadingComputing:
				wg.Add(1)
				go func() {
					defer wg.Done()
					if ftop.opFunc(ctx, o, xv, out) {
						end = true
					}
				}()
			default:
			}
		}
		wg.Wait() //waiting all go-routines completed
		o.closeFlow(out)
	}()
}

//Distinct operator filters an Observable by only allowing items through that have not already been emitted
func (parent *Observable) Distinct() (o *Observable) {
	o = parent.newFilterObservable("distinct")
	o.flip_accept_error = true
	o.flip_sup_ctx = true
	m := map[string]bool{}
	o.operator = filterOperator{
		opFunc: func(ctx context.Context, o *Observable, item reflect.Value, out chan interface{}) (end bool) {
			itemStr := fmt.Sprintf("%v", item)
			if _, ok := m[itemStr]; !ok {
				m[itemStr] = true
				o.sendToFlow(ctx, item.Interface(), out)
			}
			return false
		},
	}
	return o
}

//ElementAt operator pulls an item located at a specified index location
func (parent *Observable) ElementAt(loc int) (o *Observable) {
	o = parent.newFilterObservable("elementAt.n")
	o.flip_accept_error = true
	o.flip_sup_ctx = true
	location := 0
	o.operator = filterOperator{
		opFunc: func(ctx context.Context, o *Observable, item reflect.Value, out chan interface{}) (end bool) {
			if location == loc {
				o.sendToFlow(ctx, item.Interface(), out)
				return true
			}
			location++
			return false
		},
	}
	return o
}

//Skip ignores the first n items
func (parent *Observable) Skip(start int) (o *Observable) {
	o = parent.newFilterObservable("skip.n")
	o.flip_accept_error = true
	o.flip_sup_ctx = true
	location := 0
	o.operator = filterOperator{
		opFunc: func(ctx context.Context, o *Observable, item reflect.Value, out chan interface{}) (end bool) {
			location++
			if location > start {
				o.sendToFlow(ctx, item.Interface(), out)
			}
			return false
		},
	}
	return o
}

//First emits only the first item
func (parent *Observable) First() (o *Observable) {
	o = parent.newFilterObservable("first")
	o.flip_accept_error = true
	o.flip_sup_ctx = true
	o.operator = filterOperator{
		opFunc: func(ctx context.Context, o *Observable, item reflect.Value, out chan interface{}) (end bool) {
			o.sendToFlow(ctx, item.Interface(), out)
			return true
		},
	}
	return o
}

//SkipLast suppress the final n items emitted by an Observable
func (parent *Observable) SkipLast(num int) (o *Observable) {
	o = parent.newFilterObservable("skipLast.n")
	o.flip_accept_error = true
	o.flip_sup_ctx = true
	var lasts []interface{}
	count := 0
	o.operator = filterOperator{
		opFunc: func(ctx context.Context, o *Observable, item reflect.Value, out chan interface{}) (end bool) {
			if count == num {
				o.sendToFlow(ctx, lasts[0], out)
				lasts = lasts[1:]
			} else {
				count++
			}
			lasts = append(lasts, item.Interface())
			return false
		},
	}
	return o
}

// 参考transform.go中的newTransformObservable
func (parent *Observable) newFilterObservable(name string) (o *Observable) {
	//new Observable
	o = newObservable()
	o.Name = name

	//chain Observables
	parent.next = o
	o.pred = parent
	o.root = parent.root

	//set options
	o.buf_len = BufferLen
	return o
}
